// 扫码业务关系建立系统
// 
// 业务逻辑：销售人员扫采购人员个人码 -> 建立销售公司与采购公司的业务关系
// 采购公司其他员工也能看到相关业务信息

// ============= 扫码业务模型 =============

// 1. 二维码模型
class QRCode {
    constructor(data) {
        this.id = data.id;
        this.type = data.type; // 'personal', 'company'
        this.ownerId = data.ownerId; // 用户ID或公司ID
        this.code = data.code; // 二维码唯一标识
        this.expireTime = data.expireTime;
        this.status = 'active'; // active, expired, used
        this.scannedBy = []; // 扫码记录
        this.createdAt = new Date();
    }

    // 验证二维码有效性
    isValid() {
        return this.status === 'active' && 
               (!this.expireTime || this.expireTime > new Date());
    }

    // 记录扫码
    recordScan(scannerId, scanTime = new Date()) {
        this.scannedBy.push({
            scannerId,
            scanTime,
            scanResult: null
        });
    }

    // 获取二维码信息
    getQRInfo() {
        return {
            id: this.id,
            type: this.type,
            code: this.code,
            status: this.status,
            isValid: this.isValid(),
            createdAt: this.createdAt
        };
    }
}

// 2. 扫码业务关系模型
class ScanBusinessRelationship {
    constructor(data) {
        this.id = data.id;
        this.scannerUserId = data.scannerUserId; // 扫码用户ID
        this.scannerCompanyId = data.scannerCompanyId; // 扫码用户所属公司ID
        this.targetUserId = data.targetUserId; // 被扫码用户ID
        this.targetCompanyId = data.targetCompanyId; // 被扫码用户所属公司ID
        this.qrCodeId = data.qrCodeId; // 扫描的二维码ID
        this.relationshipType = data.relationshipType; // 'sales_to_purchase', 'supplier_to_customer'
        this.status = data.status || 'pending'; // pending, active, suspended, terminated
        this.businessTerms = data.businessTerms || {};
        this.permissions = data.permissions || []; // 采购公司其他员工的查看权限
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }

    // 验证业务关系
    validate() {
        const issues = [];

        if (this.scannerCompanyId === this.targetCompanyId) {
            issues.push('不能与自己公司建立业务关系');
        }

        if (!this.scannerUserId || !this.targetUserId) {
            issues.push('扫码用户和目标用户不能为空');
        }

        return {
            isValid: issues.length === 0,
            issues
        };
    }

    // 获取关系描述
    getRelationshipDescription() {
        const descriptions = {
            'sales_to_purchase': '销售对采购业务关系',
            'supplier_to_customer': '供应商对客户业务关系'
        };
        return descriptions[this.relationshipType] || '未知业务关系';
    }

    // 检查用户是否有权限查看此关系
    canUserView(userId, userCompanyId) {
        // 扫码用户和被扫码用户可以查看
        if (userId === this.scannerUserId || userId === this.targetUserId) {
            return true;
        }

        // 两个公司的员工都可以查看（如果设置了相应权限）
        if (userCompanyId === this.scannerCompanyId || userCompanyId === this.targetCompanyId) {
            return this.permissions.includes('company_view');
        }

        return false;
    }
}

// 3. 扫码业务记录模型
class ScanBusinessRecord {
    constructor(data) {
        this.id = data.id;
        this.relationshipId = data.relationshipId; // 关联的业务关系ID
        this.scanType = data.scanType; // 'relationship_establish', 'order_create', 'product_view'
        this.scannerUserId = data.scannerUserId;
        scannerCompanyId = data.scannerCompanyId;
        this.targetUserId = data.targetUserId;
        this.targetCompanyId = data.targetCompanyId;
        this.businessData = data.businessData || {}; // 业务数据
        this.scanResult = data.scanResult || 'success'; // success, failed, pending
        this.notes = data.notes || '';
        this.createdAt = new Date();
    }

    // 获取业务记录摘要
    getSummary() {
        return {
            id: this.id,
            scanType: this.scanType,
            scannerUserId: this.scannerUserId,
            targetUserId: this.targetUserId,
            scanResult: this.scanResult,
            createdAt: this.createdAt
        };
    }
}

// ============= 扫码业务服务 =============

class ScanBusinessService {
    constructor() {
        this.qrCodes = new Map();
        this.relationships = new Map();
        this.businessRecords = new Map();
    }

    // 生成个人二维码
    async generatePersonalQRCode(userId, companyId, options = {}) {
        const qrCode = new QRCode({
            id: `qr_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            type: 'personal',
            ownerId: userId,
            code: this.generateQRCode(),
            expireTime: options.expireTime,
            status: 'active'
        });

        // 附加用户和公司信息
        qrCode.userInfo = { userId, companyId };
        this.qrCodes.set(qrCode.id, qrCode);
        
        return qrCode;
    }

    // 生成公司二维码
    async generateCompanyQRCode(companyId, options = {}) {
        const qrCode = new QRCode({
            id: `qr_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            type: 'company',
            ownerId: companyId,
            code: this.generateQRCode(),
            expireTime: options.expireTime,
            status: 'active'
        });

        qrCode.companyInfo = { companyId };
        this.qrCodes.set(qrCode.id, qrCode);
        
        return qrCode;
    }

    // 生成唯一二维码
    generateQRCode() {
        return `SCAN_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }

    // 扫码处理 - 核心业务逻辑
    async scanQRCode(scannerUserId, scannerCompanyId, qrCode, scanType = 'relationship_establish') {
        // 验证二维码
        if (!qrCode.isValid()) {
            throw new Error('二维码已失效');
        }

        // 记录扫码
        qrCode.recordScan(scannerUserId);

        let relationship;
        
        if (qrCode.type === 'personal') {
            // 扫个人码 - 建立公司间业务关系
            relationship = await this.handlePersonalQRCodeScan(
                scannerUserId, scannerCompanyId, qrCode, scanType
            );
        } else if (qrCode.type === 'company') {
            // 扫公司码 - 直接建立公司关系
            relationship = await this.handleCompanyQRCodeScan(
                scannerCompanyId, qrCode, scanType
            );
        }

        // 创建业务记录
        const record = new ScanBusinessRecord({
            id: `record_${Date.now()}`,
            relationshipId: relationship.id,
            scanType,
            scannerUserId,
            scannerCompanyId,
            targetUserId: qrCode.type === 'personal' ? qrCode.userInfo.userId : null,
            targetCompanyId: qrCode.type === 'personal' ? qrCode.userInfo.companyId : qrCode.companyInfo.companyId,
            scanResult: 'success'
        });

        this.businessRecords.set(record.id, record);
        
        return { relationship, record };
    }

    // 处理个人二维码扫描
    async handlePersonalQRCodeScan(scannerUserId, scannerCompanyId, qrCode, scanType) {
        const targetUserId = qrCode.userInfo.userId;
        const targetCompanyId = qrCode.userInfo.companyId;

        // 检查是否已存在业务关系
        const existingRelationship = this.findExistingRelationship(
            scannerCompanyId, targetCompanyId
        );

        if (existingRelationship) {
            // 已存在关系，更新状态
            existingRelationship.status = 'active';
            existingRelationship.updatedAt = new Date();
            return existingRelationship;
        }

        // 创建新的业务关系
        const relationship = new ScanBusinessRelationship({
            id: `rel_${Date.now()}`,
            scannerUserId,
            scannerCompanyId,
            targetUserId,
            targetCompanyId,
            qrCodeId: qrCode.id,
            relationshipType: 'sales_to_purchase',
            status: 'active',
            permissions: ['company_view'], // 采购公司其他员工可以查看
            businessTerms: {
                establishedVia: 'personal_qr_scan',
                establishedAt: new Date(),
                autoApproval: true
            }
        });

        const validation = relationship.validate();
        if (!validation.isValid) {
            throw new Error(`业务关系验证失败: ${validation.issues.join(', ')}`);
        }

        this.relationships.set(relationship.id, relationship);
        return relationship;
    }

    // 处理公司二维码扫描
    async handleCompanyQRCodeScan(scannerCompanyId, qrCode, scanType) {
        const targetCompanyId = qrCode.companyInfo.companyId;

        // 检查是否已存在业务关系
        const existingRelationship = this.findExistingRelationship(
            scannerCompanyId, targetCompanyId
        );

        if (existingRelationship) {
            existingRelationship.status = 'active';
            existingRelationship.updatedAt = new Date();
            return existingRelationship;
        }

        // 创建新的业务关系
        const relationship = new ScanBusinessRelationship({
            id: `rel_${Date.now()}`,
            scannerUserId: null,
            scannerCompanyId,
            targetUserId: null,
            targetCompanyId,
            qrCodeId: qrCode.id,
            relationshipType: 'supplier_to_customer',
            status: 'active',
            permissions: ['company_view'],
            businessTerms: {
                establishedVia: 'company_qr_scan',
                establishedAt: new Date()
            }
        });

        const validation = relationship.validate();
        if (!validation.isValid) {
            throw new Error(`业务关系验证失败: ${validation.issues.join(', ')}`);
        }

        this.relationships.set(relationship.id, relationship);
        return relationship;
    }

    // 查找现有业务关系
    findExistingRelationship(companyId1, companyId2) {
        for (const relationship of this.relationships.values()) {
            if ((relationship.scannerCompanyId === companyId1 && relationship.targetCompanyId === companyId2) ||
                (relationship.scannerCompanyId === companyId2 && relationship.targetCompanyId === companyId1)) {
                return relationship;
            }
        }
        return null;
    }

    // 获取用户可查看的业务关系
    async getUserViewableRelationships(userId, userCompanyId) {
        const viewableRelationships = [];

        for (const relationship of this.relationships.values()) {
            if (relationship.canUserView(userId, userCompanyId)) {
                viewableRelationships.push(relationship);
            }
        }

        return viewableRelationships;
    }

    // 获取公司的所有业务关系
    async getCompanyRelationships(companyId) {
        const companyRelationships = [];

        for (const relationship of this.relationships.values()) {
            if (relationship.scannerCompanyId === companyId || 
                relationship.targetCompanyId === companyId) {
                companyRelationships.push(relationship);
            }
        }

        return companyRelationships;
    }

    // 获取业务关系历史记录
    async getRelationshipHistory(relationshipId) {
        const records = [];

        for (const record of this.businessRecords.values()) {
            if (record.relationshipId === relationshipId) {
                records.push(record);
            }
        }

        return records.sort((a, b) => b.createdAt - a.createdAt);
    }
}

// ============= 权限控制服务 =============

class PermissionService {
    constructor(scanBusinessService) {
        this.scanBusinessService = scanBusinessService;
    }

    // 检查用户是否有权限查看业务关系
    async canViewRelationship(userId, userCompanyId, relationshipId) {
        const relationship = this.scanBusinessService.relationships.get(relationshipId);
        
        if (!relationship) {
            return false;
        }

        return relationship.canUserView(userId, userCompanyId);
    }

    // 检查用户是否有权限管理业务关系
    async canManageRelationship(userId, userCompanyId, relationshipId) {
        const relationship = this.scanBusinessService.relationships.get(relationshipId);
        
        if (!relationship) {
            return false;
        }

        // 只有建立关系的用户或公司管理员可以管理
        return userId === relationship.scannerUserId || 
               userId === relationship.targetUserId ||
               userCompanyId === relationship.scannerCompanyId ||
               userCompanyId === relationship.targetCompanyId;
    }

    // 获取用户在业务关系中的权限
    async getUserRelationshipPermissions(userId, userCompanyId, relationshipId) {
        const relationship = this.scanBusinessService.relationships.get(relationshipId);
        
        if (!relationship) {
            return [];
        }

        const permissions = [];

        // 基础查看权限
        if (relationship.canUserView(userId, userCompanyId)) {
            permissions.push('view');
        }

        // 管理权限
        if (await this.canManageRelationship(userId, userCompanyId, relationshipId)) {
            permissions.push('manage');
        }

        return permissions;
    }
}

// ============= 使用示例 =============

// 初始化服务
const scanBusinessService = new ScanBusinessService();
const permissionService = new PermissionService(scanBusinessService);

// 模拟业务场景
async function demonstrateBusinessScenario() {
    console.log('=== 扫码业务关系建立演示 ===\n');

    // 1. 采购人员B生成个人二维码
    const purchaseUserB = { id: 'user_b', name: '采购人员B', companyId: 'company_purchase' };
    const purchaseCompanyB = { id: 'company_purchase', name: '采购公司B' };
    
    const personalQRCode = await scanBusinessService.generatePersonalQRCode(
        purchaseUserB.id, 
        purchaseCompanyB.id,
        { expireTime: new Date(Date.now() + 24 * 60 * 60 * 1000) } // 24小时有效期
    );

    console.log('1. 采购人员B生成个人二维码');
    console.log('   二维码信息:', personalQRCode.getQRInfo());
    console.log('   关联用户:', purchaseUserB.name);
    console.log('   关联公司:', purchaseCompanyB.name);
    console.log();

    // 2. 销售人员A扫描采购人员B的个人二维码
    const salesUserA = { id: 'user_a', name: '销售人员A', companyId: 'company_sales' };
    const salesCompanyA = { id: 'company_sales', name: '销售公司A' };

    const scanResult = await scanBusinessService.scanQRCode(
        salesUserA.id,
        salesCompanyA.id,
        personalQRCode,
        'relationship_establish'
    );

    console.log('2. 销售人员A扫描采购人员B的个人二维码');
    console.log('   扫码用户:', salesUserA.name);
    console.log('   关系建立:', scanResult.relationship.getRelationshipDescription());
    console.log('   关系状态:', scanResult.relationship.status);
    console.log('   权限设置:', scanResult.relationship.permissions);
    console.log();

    // 3. 采购公司B的其他员工也能看到这个关系
    const purchaseUserC = { id: 'user_c', name: '采购员工C', companyId: 'company_purchase' };
    const viewableRelationships = await scanBusinessService.getUserViewableRelationships(
        purchaseUserC.id,
        purchaseUserC.companyId
    );

    console.log('3. 采购公司B的其他员工查看业务关系');
    console.log('   查看用户:', purchaseUserC.name);
    console.log('   可查看关系数量:', viewableRelationships.length);
    console.log('   关系详情:', viewableRelationships[0].getRelationshipDescription());
    console.log();

    // 4. 权限检查
    const canView = await permissionService.canViewRelationship(
        purchaseUserC.id,
        purchaseUserC.companyId,
        scanResult.relationship.id
    );

    console.log('4. 权限检查');
    console.log('   采购员工C是否有权限查看:', canView);
    console.log();

    // 5. 获取业务关系历史
    const history = await scanBusinessService.getRelationshipHistory(scanResult.relationship.id);
    console.log('5. 业务关系历史记录');
    console.log('   历史记录数量:', history.length);
    console.log('   最新记录:', history[0].getSummary());
    console.log();

    return {
        relationship: scanResult.relationship,
        record: scanResult.record,
        personalQRCode,
        viewableRelationships
    };
}

// 导出模块
export {
    QRCode,
    ScanBusinessRelationship,
    ScanBusinessRecord,
    ScanBusinessService,
    PermissionService,
    demonstrateBusinessScenario
};